package com.handy.service.activiti.impl;

import com.handy.service.activiti.IWorkFlowRepositoryService;
import com.handy.vo.PageBean;
import lombok.RequiredArgsConstructor;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.image.ProcessDiagramGenerator;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @author handy
 */
@Service
@RequiredArgsConstructor
public class WorkFlowRepositoryServiceImpl implements IWorkFlowRepositoryService {
    private final RepositoryService repositoryService;

    /**
     * 流程部署列表
     *
     * @param pageBean 参数
     * @return 部署列表
     */
    @Override
    public List<Deployment> deployList(PageBean pageBean) {
        return repositoryService.createDeploymentQuery().orderByDeploymentId().desc().listPage((pageBean.getPage().intValue() - 1), pageBean.getLimit().intValue());
    }

    /**
     * 获取模型列表
     *
     * @param pageBean 参数
     * @return 模型列表
     */
    @Override
    public List<ProcessDefinition> getProcessList(PageBean pageBean) {
        return repositoryService.createProcessDefinitionQuery().orderByDeploymentId().desc().listPage((pageBean.getPage().intValue() - 1), pageBean.getLimit().intValue());
    }

    /**
     * 查看定义的流程图
     *
     * @param processDefinitionId 流程定义Id
     * @return 流程图
     */
    @Override
    public byte[] definitionImage(String processDefinitionId) {
        try {
            BpmnModel model = repositoryService.getBpmnModel(processDefinitionId);
            if (model != null && model.getLocationMap().size() > 0) {
                ProcessDiagramGenerator generator = new DefaultProcessDiagramGenerator();
                InputStream imageStream = generator.generateDiagram(model, "png", new ArrayList<>());
                byte[] buffer = new byte[imageStream.available()];
                imageStream.read(buffer);
                imageStream.close();
                return buffer;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
